package com.lovo.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet(name = "UploadServlet",urlPatterns = "/upload.do")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String realPath = this.getServletContext().getRealPath("/img");
        System.out.println("realPath = " + realPath);
        File file = new File(realPath);
        if(!file.exists() && !file.isDirectory()){
            System.out.println(realPath + "目录不存在需要创建");
            file.mkdir();
        }
        String value = "";
        try {
            //创建工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //创建文件的上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //需要解决文件上传中乱码问题
            upload.setHeaderEncoding("UTF-8");
            //判断页面是否有没有from 表单的限定
            if(!ServletFileUpload.isMultipartContent(request)){
                System.out.println("这里会进来吗");
                return;
            }
            //设置单个文件上传大小
            upload.setFileSizeMax(1024*1024);
            //设置上传文件总大小
            upload.setSizeMax(1024*1024*10);
            //使用ServletFileUpload解析上传数据
            List<FileItem> fileItems = null;

            fileItems = upload.parseRequest(request);

            //从集合中遍历出所有的值
            for (FileItem fileItem:fileItems) {
                //判断是不是一般的键值对
                if(!fileItem.isFormField()){
                    //获取上传文件的名字
                    String fileName = fileItem.getName();
                    System.out.println("fileName = " + fileName);
                    //如果上传文件名字为空直接进入下一个循环
                    if (fileName == null && fileName.trim().equalsIgnoreCase("")){
                        continue;
                    }
                    //获取文件的全名
                    fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                    //通过文件流，将文件保存到指定的服务器路径
                    InputStream in = fileItem.getInputStream();
                    //输出流
                    //输出流保存只是为了把图片保存到真实的物理地址中去，但在开发时应该是以项目为基础，所以数据库中的地址应该和物理地址不一样，应该是项目的地址
                    FileOutputStream out = new FileOutputStream(realPath + "/" + fileName);
//                    FileOutputStream out = new FileOutputStream("C:\Users\Administrator\IdeaProjects\Pests\src\main\webapp\img" + "/" + fileName);
//                    FileOutputStream out = new FileOutputStream("C:/Users/Administrator/Desktop/1212" + "/" + fileName);
                    //使用变量保存地址存在数据库中
                    value = "/api/petSystem/img/"+fileName;
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = in.read(buffer))>0){
                        out.write(buffer,0,len);
                    }
                    in.close();
                    out.close();
                    //删除每次产生的临时文件
                    fileItem.delete();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String json = "{\"code\":0,\"msg\":0,\"data\":{\"path\":\""+value+"\"}}";
        System.out.println("json="+json);
        response.getWriter().write(json);
    }
}
